<template>
  <view class="container">
    <view class="search-box">
      <uni-search-bar @confirm="handleSearch" placeholder="搜索集装箱号"></uni-search-bar>
      <view class="filter-row">
        <picker mode="date" fields="month" @change="handleMonthChange">
          <view class="picker">{{ currentMonth }}</view>
        </picker>
        <picker @change="handleTypeChange" :range="containerTypes">
          <view class="picker">{{ selectedType || '全部类型' }}</view>
        </picker>
      </view>
    </view>
    
    <scroll-view scroll-y class="list-container" @scrolltolower="loadMore">
      <view class="list-item" v-for="item in list" :key="item.id" @click="goToDetail(item.id)">
        <view class="item-header">
          <text class="container-number">{{ item.container_number }}</text>
          <text class="container-type">{{ item.container_type }}</text>
        </view>
        <view class="item-content">
          <text class="date">{{ item.loading_date }}</text>
          <text class="car">{{ item.car || '未指定车辆' }}</text>
        </view>
        <view class="item-footer">
          <text class="location">{{ item.pickup_location }} → {{ item.loading_location }} → {{ item.dropoff_location }}</text>
          <text class="fee">¥{{ item.pickup_return_fee }}</text>
        </view>
      </view>
      
      <uni-load-more :status="loadingStatus"></uni-load-more>
    </scroll-view>
    
    <view class="floating-buttons">
      <button class="add-button" @click="goToAdd">+</button>
      <button class="stats-button" @click="goToStats">统计</button>
    </view>
  </view>
</template>

<script>
import api from '@/store/work_api.js';
import uniSearchBar from '@dcloudio/uni-ui/lib/uni-search-bar/uni-search-bar.vue';
import uniLoadMore from '@dcloudio/uni-ui/lib/uni-load-more/uni-load-more.vue';

export default {
	components: {
	    uniSearchBar,
	    uniLoadMore
	  },
  data() {
    return {
      list: [],
      loadingStatus: 'more',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchText: '',
      currentMonth: this.formatDate(new Date(), 'YYYY-MM'),
      selectedType: '',
      containerTypes: ['20GP', '20HC', '40GP', '40HQ', '40RT', '40TR', '40HC', '45HC', '45GP', '其他']
    }
  },
  onLoad() {
	  
	    const userId = uni.getStorageSync('userId');
	    
	    if (!userId) {
	      uni.showToast({ 
	        title: '请先登录', 
	        icon: 'none',
	        duration: 2000
	      });
	      
	      // 使用switchTab而不是redirectTo跳转Tabbar页面
	      setTimeout(() => {
	        uni.switchTab({ 
	          url: '/pages/user/login',
	          fail: (err) => {
	            console.error('跳转失败:', err);
	            uni.navigateTo({ url: '/pages/user/login' });
	          }
	        });
	      }, 1500);
	      return;
	    }
	    
	    this.loadData();
  },
  methods: {
    formatDate(date, fmt) {
      // 日期格式化函数
      const o = {
        'M+': date.getMonth() + 1,
        'D+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    },
    
    async loadData(reset = false) {
      if (this.loadingStatus === 'loading') return;
      
      this.loadingStatus = 'loading';
      
      if (reset) {
        this.currentPage = 1;
        this.list = [];
      }
      
      try {
        const [startDate, endDate] = this.getMonthRange(this.currentMonth);
        // 获取用户ID
        const userId = uni.getStorageSync('userId');
		if (!userId) {
		    uni.showToast({ title: '请先登录', icon: 'none' });
		    return;
		}
        const res = await api.getWorkRecords({
          page: this.currentPage,
          pageSize: this.pageSize,
          container_number: this.searchText,
          start_date: startDate,
          end_date: endDate,
          container_type: this.selectedType === '全部类型' ? '' : this.selectedType,
		  user_id: userId // 添加用户ID参数
        });
        
        if (res.statusCode !== 200 || res.data.status !== 'success') {
          uni.showToast({
            title: '加载失败' + (res.data.message || '未知错误'),
            icon: 'none'
          });
          this.loadingStatus = 'more';
          return;
        }
        // 正确获取数据数组
        const responseData = res.data.data;
        this.total = res.data.total;
        this.list = this.list.concat(responseData);
        if (this.list.length >= this.total) {
          this.loadingStatus = 'noMore';
        } else {
          this.loadingStatus = 'more';
          this.currentPage++;
        }
      } catch (err) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
        this.loadingStatus = 'more';
      }
    },
    
    getMonthRange(month) {
      const year = parseInt(month.split('-')[0]);
      const monthNum = parseInt(month.split('-')[1]);
      const startDate = new Date(year, monthNum - 1, 1);
      const endDate = new Date(year, monthNum, 0);
      
      return [
        this.formatDate(startDate, 'YYYY-MM-DD'),
        this.formatDate(endDate, 'YYYY-MM-DD')
      ];
    },
    
    handleSearch(e) {
      this.searchText = e.value;
      this.loadData(true);
    },
    
    handleMonthChange(e) {
      this.currentMonth = e.detail.value;
      this.loadData(true);
    },
    
    handleTypeChange(e) {
      this.selectedType = this.containerTypes[e.detail.value];
      this.loadData(true);
    },
    
    loadMore() {
      // 只有在状态为'more'时才加载更多
	  if (this.loadingStatus === 'more') {
		this.loadData();
	  }
    },
    
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/work/detail?id=${id}`
      });
    },
    
    goToAdd() {
      uni.navigateTo({
        url: '/pages/work/add'
      });
    },
    
    goToStats() {
      uni.navigateTo({
        url: '/pages/work/stats'
      });
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.search-box {
  margin-bottom: 20rpx;
}

.filter-row {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
}

.picker {
  background-color: #f5f5f5;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.list-container {
  flex: 1;
  overflow: hidden;
}

.list-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.container-number {
  font-size: 32rpx;
  font-weight: bold;
}

.container-type {
  background-color: #f0f0f0;
  padding: 5rpx 15rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.item-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
  color: #666;
  font-size: 28rpx;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
}

.location {
  color: #666;
  flex: 1;
  margin-right: 20rpx;
}

.fee {
  color: #e74c3c;
  font-weight: bold;
}

.floating-buttons {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  display: flex;
  flex-direction: column;
}

.add-button, .stats-button {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #3498db;
  color: white;
  font-size: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
}

.stats-button {
  background-color: #2ecc71;
  font-size: 28rpx;
}
</style>